package com.sgj.common.config;

import com.sgj.common.domain.service.impl.MyUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author 沈国纪
 * @date 2021/12/18 20:54
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private MyUserDetailsServiceImpl myUserDetailsService;

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(myUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 配置无权限访问跳转页面
		http.exceptionHandling().accessDeniedPage("/unauth.html");
		// 自定义
		http.formLogin()
			// 登陆页面设置
			.loginPage("/static/login.html")
			// 登录访问路径
			.loginProcessingUrl("/user/login")
			// 登陆成功跳转路径
			.defaultSuccessUrl("/test/index").permitAll()
			.and().authorizeRequests()
			// 放行路径,无需认证
			.antMatchers(
					"/",
					"/test/hello",
					"/user/login",
					"/doc.html/**",
					"/webjars/**",
					"/img.icons/**",
					"/swagger-resources/**",
					"/v2/api-docs"
			).permitAll()
			// .antMatchers("/test/index").hasAuthority("admin")
			// .antMatchers("/test/index").hasAnyAuthority("admin,guest")
			.antMatchers("/test/index").hasRole("sale")
			.anyRequest().authenticated()
			// 关闭csrf防护
			.and().csrf().disable();
	}
}